<?php
namespace Api\Controller;

/**
 * 地理位置
 * Class LocationController
 * @package Api\Controller
 */
class LocationController extends BaseRestController {

    /**
     * 显示列表信息
     */
    public function page() {
        $curPage = I('curPage', 1, 'int');
        $pageSize = I('pageSize', 50, 'int');
        $curPage = $curPage <= 1 ? 0 : $curPage - 1;
        $installationId = I('iId', '');

        $location = M("Location");
        $location = $location->limit($pageSize * $curPage . ',' . ($curPage + 1) * $pageSize)->order('id desc');
        if (!empty($installationId)) {
            $location = $location->where("installationId = '%s'", $installationId);
        }
        $list = $location->select();
        $count = $location->count();

        foreach ($list as $k => &$v) {
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            $v['latitude'] = round($v['latitude'], 6);
            $v['lontitude'] = round($v['lontitude'], 6);
        }

        $data['status']  = 200;
        $data['success'] = true;
        $data['curPage'] = $curPage + 1;
        $data['totalRows'] = intval($count);
        $data['data'] = $list;
        $this->response($data, 'json');
    }

    /**
     * 添加 位置信息 入库
     */
    public function add() {
        switch ($this->_method){
            case 'post' :
                $location = M("Location");

                $latitude = I('latitude', '');
                $lontitude = I('lontitude', '');
                $installationId = I('installationId', '');
                if (empty($latitude) || empty($lontitude)) {
                    $this->response(array('status' => 400, 'message' => 'error parameter!'), 'json');
                    return;
                }

                $location->latitude = $latitude;
                $location->lontitude = $lontitude;
                $location->installationId = $installationId;
                $location->radius = I('radius', 0);
                $location->addr = I('addr', '');
                $location->locationDescribe = I('locationDescribe', '');
                $location->poilist = I('poilist', '', false);
                $location->createTime = time();
                $location->add();

                $this->responseSuccessJson();
                break;
            default :
                $this->response404Json();
                break;
        }


    }

    public function delete() {
        switch ($this->_method) {
            case 'delete' :
                $id = I('id', 00, 'int');
                if ($id > 0) {
                    $location = M("Location");
                    $location->delete($id);
                } else {
                    $this->response404Json();
                }
                break;
            default :
                $this->response404Json();
                break;
        }
    }

}